//
//  QKNetworkTools.swift
//  微博
//
//  Created by qiukai on 16/4/9.
//  Copyright © 2016年 仇恺. All rights reserved.
//

import UIKit
import AFNetworking
enum QKRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class QKNetworkTools: AFHTTPSessionManager {
    // MARK: - 应用程序信息
    private let appKey = "3863118655"
    private let appSecret = "b94c088ad2cdae8c3b9641852359d28c"
    private let redirectUrl = "http://www.baidu.com"
    // MARK: - 网络请求回调
    typealias QKRequestCallBack = (result: AnyObject?, error: NSError?)->()
    
    //单例
    static let sharedTools: QKNetworkTools = {
        let tools = QKNetworkTools(baseURL: nil)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    
}
// MARK: - OAuth相关方法
extension QKNetworkTools{
    /// OAuth 授权 URL
    /// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthURL: NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        
        return NSURL(string: urlString)!
    }

    // MARK: - 加载AccessToken
    func loadAccessToken(code: String, finished: QKRequestCallBack){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": appKey,
                      "client_secret": appSecret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": redirectUrl]
        request(.POST, URLString: urlString, paramters: params, finished: finished)
    }
    
}

// MARK: - 封装AFN网络方法
extension QKNetworkTools{
    /// AFN网络方法
    ///
    /// - parameter method:    POST/GET
    /// - parameter URLString: URLString
    /// - parameter paramters: 参数字典
    /// - parameter finished:  完成回调
    private func request(method: QKRequestMethod, URLString: String, paramters: [String: AnyObject]?, finished: QKRequestCallBack){
        
        let success = { (tank: NSURLSessionDataTask, result: AnyObject?) -> Void in
            finished(result: result, error: nil)
        }
        
        let failure = { (tank: NSURLSessionDataTask?, error: NSError) -> Void in
            print(error)
            finished(result: nil, error: error)
        }
        
        if method == QKRequestMethod.GET{
            GET(URLString, parameters: paramters, success: success, failure: failure)
        }else{
            POST(URLString, parameters: paramters, success: success, failure: failure)
        }
    }
}